import {getResource, getButtonUser} from '@/api/system'
import db from '@/utils/localstorage'
export default {
  namespaced: true,
  state: () => ({
    routes: db.get('viewRoutes', []),
    btnResource: db.get('btnResource', []),
  }),
  mutations:{
    setRoutes(state, val) {
      state.routes = val
      db.save('viewRoutes', val)
    },
    setResource(state, val) {
      state.btnResource = val
      db.save('btnResource', val)
    }
  },
  actions:{
    async generateRoutes({ commit }) {
      return new Promise((resolve, reject) => {
        getResource().then(res => {
          let { data, code } = res
          if(code !== 0){
            data = []
          }
          // 设置菜单组
          commit('setRoutes', data)
          resolve(data)
        }).catch((err) => {
          console.error('菜单加载异常', err)
          reject(err)
        })
      })
    },
    async generateButton({ commit }) {
      return new Promise((resolve, reject) => {
        getButtonUser().then(res => {
          if(res.code === 0){
            let _arr = [], data = res.data || []
            for(let i = 0, len = data.length; i < len; i++) {
              _arr.push(res.data[i].code)
            }
            // 设置菜单组
            commit('setResource', _arr)
            resolve(_arr)
          }
        }).catch((err) => {
          console.error('菜单加载异常', err)
          reject(err)
        })
      })
    }
  }
}